package com.bw.finance.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.bw.finance.client.FinanceEsClient;
import com.bw.finance.client.FinanceborrowClient;
import com.bw.finance.conf.OrderMqConfig;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.es.BorrowBiao;
import com.bw.finance.eneity.invest.BiaoInfo;
import com.bw.finance.eneity.invest.EbankBackPlan;
import com.bw.finance.eneity.invest.EbankInvestLog;
import com.bw.finance.eneity.locana.EbankBidInfo;
import com.bw.finance.eneity.locana.EbankLoanInfo;
import com.bw.finance.eneity.user.EbankInvestor;
import com.bw.finance.service.*;
import com.bw.finance.utils.Freemark.FreemarkUtils;
import com.bw.finance.websocket.MsgWsService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
@RabbitListener(queues = {OrderMqConfig.QUEUE_ORDER})
public class Consume {

    @Autowired
    private MsgWsService msgWsService;

    @Autowired
    private IEbankBidInfoService bidInfoService;

    @Autowired
    private IEbankLoanInfoService loanInfoService;

    @Autowired
    private FinanceEsClient financeEsClient;

    @Autowired
    private IEbankInvestLogService investLogService;

    @Autowired
    private IEbankInvestorService investorService;

    @Autowired
    private IEbankBackPlanService backPlanService;

    @Autowired
    private FinanceborrowClient financeborrowClient;

    private static final Logger log = LoggerFactory.getLogger(Consume.class);

    @RabbitHandler
    public void saveorder(Map map, Message message, Channel channel){
        ResponseResult result = ResponseResult.FAIL();
        Long bid= (Long) map.get("bid");
        Long uid= (Long) map.get("uid");
        BigDecimal money= (BigDecimal) map.get("money");
        try {
            EbankBidInfo bidInfo = bidInfoService.getById(bid);
            EbankLoanInfo loanInfo = loanInfoService.getById(bidInfo.getLid());
            EbankInvestor investor = investorService.getById(uid);
            //跟新标的募集金额
            bidInfo.setRaiseAmount(bidInfo.getRaiseAmount().add(money));
            bidInfoService.saveOrUpdate(bidInfo);
            log.info("更新募集金额结束----------------------------");
            //跟新es数据
            BorrowBiao borrowBiao = new BorrowBiao();
            borrowBiao.setId(String.valueOf(bid));
            borrowBiao.setBidName(bidInfo.getBidName());
            borrowBiao.setBidType(bidInfo.getBidType());
            borrowBiao.setInterest(loanInfo.getInterest());
            borrowBiao.setRaiseAmount(bidInfo.getRaiseAmount());
            borrowBiao.setRepayType(loanInfo.getRepayType());
            borrowBiao.setTrem(loanInfo.getTrem());
            borrowBiao.setTremType(loanInfo.getTermType());
            borrowBiao.setTotalAmount(loanInfo.getTotalAmount());
            financeEsClient.save(borrowBiao);
            log.info("更新es数据结束----------------------------");
            //添加投资记录
            EbankInvestLog ebankInvestLog = new EbankInvestLog();
            ebankInvestLog.setBid(bid);
            ebankInvestLog.setInvestorId(uid);
            ebankInvestLog.setInvestTime(new Date());
            ebankInvestLog.setInvestAmount(money);
            investLogService.saveOrUpdate(ebankInvestLog);
            log.info("添加投资记录数据结束----------------------------");
            //更改投资人余额
            investor.setBalance(investor.getBalance().subtract(money));
            investorService.saveOrUpdate(investor);
            log.info("更改投资人余额结束----------------------------");
            //判断是否满标
            if(bidInfo.getRaiseAmount().compareTo(loanInfo.getTotalAmount())==0){
                bidInfo.setStatus(4);
                bidInfoService.saveOrUpdate(bidInfo);
            }
            if(loanInfo.getTotalAmount().subtract(bidInfo.getRaiseAmount()).compareTo(bidInfo.getMinAmount())==-1){
                bidInfo.setRaiseAmount(bidInfo.getTotalAmount());
                bidInfo.setStatus(4);
                bidInfoService.saveOrUpdate(bidInfo);
            }
            log.info("更改满标结束----------------------------");
            //更新静态页面
            BiaoInfo biaoInfo = financeborrowClient.getone(bid);
            String code = "infor.html";//模板页面的名字
            FreemarkUtils.AddToClient(biaoInfo, code);
            //生成回款计划
            if(loanInfo.getRepayType()==0){//一次性还款
                if(loanInfo.getTermType()==0){//天
                    BigDecimal bigDecimal = new BigDecimal(360);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal trem = new BigDecimal(loanInfo.getTrem());//借款期限
                    BigDecimal backamount=money.add(money.multiply(loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP)).multiply(trem));//应回款金额
                    EbankBackPlan backPlan = new EbankBackPlan();
                    backPlan.setInvestId(investor.getId());
                    backPlan.setBackNum(1);//期数
                    backPlan.setBackNo(1);//几期
                    backPlan.setBackAmount(backamount);//应回款金额
                    backPlan.setCapital(money);//回款本金
                    backPlan.setInterest(money.multiply(loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP)).multiply(trem));//回款利息
                    backPlan.setArAmount(new BigDecimal(0));//已回款金额
                    backPlan.setStatus(0);//状态
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    if(bidInfo.getInterestMode()==0){//成立日
                        cal.add(Calendar.DAY_OF_MONTH,loanInfo.getTrem());
                        backPlan.setBackDate(cal.getTime());
                    }else if(bidInfo.getInterestMode()==1){//T+1
                        cal.add(Calendar.DAY_OF_MONTH,(loanInfo.getTrem()+1));
                        backPlan.setBackDate(cal.getTime());
                    }else if(bidInfo.getInterestMode()==2){//T+2
                        cal.add(Calendar.DAY_OF_MONTH,(loanInfo.getTrem()+2));
                        backPlan.setBackDate(cal.getTime());
                    }
                    backPlanService.saveOrUpdate(backPlan);
                }
                if(loanInfo.getTermType()==1){//月
                    BigDecimal bigDecimal = new BigDecimal(12);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal trem = new BigDecimal(loanInfo.getTrem());
                    BigDecimal backamount=money.add(money.multiply(loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP)).multiply(trem));
                    EbankBackPlan backPlan = new EbankBackPlan();
                    backPlan.setInvestId(investor.getId());
                    backPlan.setBackNum(1);
                    backPlan.setBackNo(1);
                    backPlan.setBackAmount(backamount);
                    backPlan.setCapital(money);
                    backPlan.setInterest(money.multiply(loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP)).multiply(trem));
                    backPlan.setArAmount(new BigDecimal(0));
                    backPlan.setStatus(0);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    if(bidInfo.getInterestMode()==0){//成立日
                        cal.add(Calendar.DAY_OF_MONTH,(loanInfo.getTrem()*30));
                        backPlan.setBackDate(cal.getTime());
                    }else if(bidInfo.getInterestMode()==1){//T+1
                        cal.add(Calendar.DAY_OF_MONTH,(loanInfo.getTrem()*30+1));
                        backPlan.setBackDate(cal.getTime());
                    }else if(bidInfo.getInterestMode()==2){//T+2
                        cal.add(Calendar.DAY_OF_MONTH,(loanInfo.getTrem()*30+2));
                        backPlan.setBackDate(cal.getTime());
                    }
                    backPlanService.saveOrUpdate(backPlan);
                }
            }
            if(loanInfo.getRepayType()==1){//等额本金
                if(loanInfo.getTermType()==0) {//天
                    BigDecimal bigDecimal = new BigDecimal(360);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal trem = new BigDecimal(loanInfo.getTrem());
                    BigDecimal ben=money.divide(trem,4,BigDecimal.ROUND_HALF_UP);//每份本金
                    BigDecimal totalmoney=money;
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    for (int i = 1; i <=loanInfo.getTrem(); i++) {
                        EbankBackPlan backPlan = new EbankBackPlan();
                        backPlan.setInvestId(investor.getId());
                        backPlan.setBackNum(loanInfo.getTrem());
                        backPlan.setBackNo(i);
                        if (bidInfo.getInterestMode() == 0) {//成立日
                            cal.add(Calendar.DAY_OF_MONTH,i);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 1) {//T+1
                            cal.add(Calendar.DAY_OF_MONTH,i+1);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 2) {//T+2
                            cal.add(Calendar.DAY_OF_MONTH,i+2);
                            backPlan.setBackDate(cal.getTime());
                        }
                        BigDecimal lixi=totalmoney.multiply(loanInfo.getInterest().divide(bigDecimal));
                        totalmoney=totalmoney.subtract(ben);
                        backPlan.setBackAmount(ben.add(lixi));
                        backPlan.setCapital(ben);
                        backPlan.setInterest(lixi);
                        backPlan.setArAmount(new BigDecimal(0));
                        backPlan.setStatus(0);
                        backPlanService.saveOrUpdate(backPlan);
                    }
                }
                if(loanInfo.getTermType()==1) {//月
                    BigDecimal bigDecimal = new BigDecimal(12);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal trem = new BigDecimal(loanInfo.getTrem());
                    BigDecimal ben=money.divide(trem,4,BigDecimal.ROUND_HALF_UP);//每份本金
                    BigDecimal totalmoney=money;
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    for (int i = 1; i <=loanInfo.getTrem(); i++) {
                        EbankBackPlan backPlan = new EbankBackPlan();
                        backPlan.setInvestId(investor.getId());
                        backPlan.setBackNum(loanInfo.getTrem());
                        backPlan.setBackNo(i);
                        if (bidInfo.getInterestMode() == 0) {//成立日
                            cal.add(Calendar.DAY_OF_MONTH,i*30);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 1) {//T+1
                            cal.add(Calendar.DAY_OF_MONTH,i*30+1);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 2) {//T+2
                            cal.add(Calendar.DAY_OF_MONTH,i*30+2);
                            backPlan.setBackDate(cal.getTime());
                        }
                        cal.setTime(new Date());
                        BigDecimal lixi=totalmoney.multiply(loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP));
                        totalmoney=totalmoney.subtract(ben);
                        backPlan.setBackAmount(ben.add(lixi));
                        backPlan.setCapital(ben);
                        backPlan.setInterest(lixi);
                        backPlan.setArAmount(new BigDecimal(0));
                        backPlan.setStatus(0);
                        backPlanService.saveOrUpdate(backPlan);
                    }
                }
            }
            if(loanInfo.getRepayType()==2){//等额本息
                if(loanInfo.getTermType()==0) {//天
                    BigDecimal bigDecimal = new BigDecimal(360);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal trem = new BigDecimal(loanInfo.getTrem());
                    BigDecimal totalmoney=money;
                    BigDecimal yueinter=loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);//月利率
                    BigDecimal yueinter1=(new BigDecimal(1).add(yueinter)).pow(loanInfo.getTrem());//1+月利率^期限
                    BigDecimal shang=yueinter.multiply(yueinter1).multiply(money);
                    BigDecimal xia=yueinter1.subtract(new BigDecimal(1));
                    BigDecimal yueback=shang.divide(xia,4,BigDecimal.ROUND_HALF_UP);//每月还款额
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    for(int i = 1; i <=loanInfo.getTrem(); i++) {
                        EbankBackPlan backPlan = new EbankBackPlan();
                        backPlan.setInvestId(investor.getId());
                        backPlan.setBackNum(loanInfo.getTrem());
                        backPlan.setBackNo(i);
                        if (bidInfo.getInterestMode() == 0) {//成立日
                            cal.add(Calendar.DAY_OF_MONTH, i * 30);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 1) {//T+1
                            cal.add(Calendar.DAY_OF_MONTH, i * 30 + 1);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 2) {//T+2
                            cal.add(Calendar.DAY_OF_MONTH, i * 30 + 2);
                            backPlan.setBackDate(cal.getTime());
                        }
                        cal.setTime(new Date());
                        backPlan.setBackAmount(yueback);
                        BigDecimal lixi = totalmoney.multiply(loanInfo.getInterest().divide(decimal, 4, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP));
                        BigDecimal ben = yueback.subtract(lixi);
                        backPlan.setCapital(ben);
                        totalmoney = totalmoney.subtract(ben);
                        backPlan.setInterest(lixi);
                        backPlan.setArAmount(new BigDecimal(0));
                        backPlan.setStatus(0);
                        backPlanService.saveOrUpdate(backPlan);
                    }
                }
                if(loanInfo.getTermType()==1) {//月
                    BigDecimal bigDecimal = new BigDecimal(12);
                    BigDecimal decimal = new BigDecimal(100);
                    BigDecimal trem = new BigDecimal(loanInfo.getTrem());
                    BigDecimal totalmoney=money;
                    BigDecimal yueinter=loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);//月利率
                    BigDecimal yueinter1=(new BigDecimal(1).add(yueinter)).pow(loanInfo.getTrem());//1+月利率^期限
                    BigDecimal shang=yueinter.multiply(yueinter1).multiply(money);
                    BigDecimal xia=yueinter1.subtract(new BigDecimal(1));
                    BigDecimal yueback=shang.divide(xia,4,BigDecimal.ROUND_HALF_UP);//每月还款额
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    for(int i = 1; i <=loanInfo.getTrem(); i++){
                        EbankBackPlan backPlan = new EbankBackPlan();
                        backPlan.setInvestId(investor.getId());
                        backPlan.setBackNum(loanInfo.getTrem());
                        backPlan.setBackNo(i);
                        if (bidInfo.getInterestMode() == 0) {//成立日
                            cal.add(Calendar.DAY_OF_MONTH,i*30);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 1) {//T+1
                            cal.add(Calendar.DAY_OF_MONTH,i*30+1);
                            backPlan.setBackDate(cal.getTime());
                        } else if (bidInfo.getInterestMode() == 2) {//T+2
                            cal.add(Calendar.DAY_OF_MONTH,i*30+2);
                            backPlan.setBackDate(cal.getTime());
                        }
                        cal.setTime(new Date());
                        backPlan.setBackAmount(yueback);
                        BigDecimal lixi=totalmoney.multiply(loanInfo.getInterest().divide(decimal,4,BigDecimal.ROUND_HALF_UP).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP));
                        BigDecimal ben=yueback.subtract(lixi);
                        backPlan.setCapital(ben);
                        totalmoney=totalmoney.subtract(ben);
                        backPlan.setInterest(lixi);
                        backPlan.setArAmount(new BigDecimal(0));
                        backPlan.setStatus(0);
                        backPlanService.saveOrUpdate(backPlan);
                    }
                }
            }
            log.info("生成回款计划结束----------------------------");
            result.setSuccess(true);
            result.setMessage("恭喜你，投标成功！！！！");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            result.setMessage("投标异常，请稍后再试！！！");
        }
        String res = JSON.toJSONString(result);
        msgWsService.sendMessage(String.valueOf(uid),res);
    }
}

